"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { SignOutButton, SignedIn, useAuth } from "@clerk/nextjs";

import { sidebarLinks } from "@/constants";
import { useTheme } from "next-themes";
import { useState, useEffect } from "react";

const LeftSidebar = () => {
  // 路由钩子只能用在客户端渲染,需要加“use client”
  const router = useRouter();
  const pathname = usePathname();
  const { userId } = useAuth();
  // 主题色
  const { theme } = useTheme();
  // 是否在客服端渲染
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);
  
  console.log("theme: ", theme);
  return (
    <section className="custom-scrollbar leftsidebar">
      <div className="flex w-full flex-1 flex-col gap-6 px-6">
        {sidebarLinks.map((link) => {
          const isActive =
            (pathname.includes(link.route) && link.route.length > 1) ||
            pathname === link.route;

          // 改变路径附带userId,不然无法访问
          if (link.route === "/profile") link.route = `${link.route}/${userId}`;

          return (
            <Link
              href={link.route}
              key={link.label}
              className={`leftsidebar_link ${isActive && "bg-primary-500 "}`}
            >
              <Image
                src={
                  isClient
                    ? theme === "dark"
                      ? link.imgURL
                      : link.imgURL_dark
                    : link.imgURL
                }
                // src={theme === "dark" ? link.imgURL : link.imgURL_dark}
                alt={link.label}
                width={24}
                height={24}
              />

              <p className="dark:text-light-1 text-black max-lg:hidden">
                {link.label}
              </p>
            </Link>
          );
        })}
      </div>

      <div className="mt-10 px-6">
        {/* clerk登出 */}
        <SignedIn>
          <SignOutButton signOutCallback={() => router.push("/sign-in")}>
            <div className="flex cursor-pointer gap-4 p-4">
              <Image
                src={
                  theme === "dark"
                    ? "/assets/logout.svg"
                    : "/assets/logout-dark.svg"
                }
                alt="logout"
                width={24}
                height={24}
              />

              <p className="dark:text-light-2 max-lg:hidden">Logout</p>
            </div>
          </SignOutButton>
        </SignedIn>
      </div>
    </section>
  );
};

export default LeftSidebar;
